//右滑关闭
mui.init({
	swipeBack: true,
});
// 储存交易的条码
var StockList = [];

var currentwindow;
var counts = "";
window.onload = function() {
	mui.plusReady(function() {
		var currentwindow = plus.webview.currentWebview();
		if (currentwindow.TradeOrderNO != '' && currentwindow.TradeOrderNO != undefined) {
			$("#hTradeOrderNO").val(currentwindow.TradeOrderNO);
			$("#Warehouse").val(currentwindow.ToWarehouseName);
			$("#hToWarehouseID").val(currentwindow.ToWarehouseID);
		} else {
			mui.toast("No parameters brought in。", {
				duration: '1000',
			});
		}

		$("#strCD").change(function() {
			if (this.checked) {
				mui.toast("Storage locked", {
					duration: '1000',
				});

			} else {
				mui.toast("Storage Unlock", {
					duration: '1000',
				});
			}
			$("#strCD").focus();
		});
		GetTradeInfo_Code();
		// 强制设置开关状态为开启
		document.getElementById('ledModeSwitch').checked = true;
		$('.mui-switch').addClass('mui-active');
		// 绑定输入事件
		bindInputEvents();
		// 确保开关点击事件绑定
		$(".mui-switch").off('click').on("click", function() {
			var checkbox = $(this).find("input[type='checkbox']");
			checkbox.prop("checked", !checkbox.prop("checked")).trigger("change");
			toggleLedMode();
		});

		// 关闭等待框
		plus.nativeUI.closeWaiting();

		$("#all").html("");
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 380) + 'px">No data available at the moment</a>');
		// 设置初始焦点
		document.getElementById('StorageNO').focus();
	});
}

var UserName = localStorage.getItem("UserName");

function CLEAR() {

	$("#StorageNO").val("");
	$("#LampNO").val("");
	$("#MaterialCode").val("");

	$("#StorageNO").focus();
}

//获取单据交易条码
function GetTradeInfo_Code() {
	xccFormPostAsync("api/PDA/GetTradeInBarCode", {
			TradeOrderNO: $("#hTradeOrderNO").val(),
			RState: "2",
			RType: 5
		}, function(data) {
			if (data.Items != null && data.Items.length > 0) {
				for (var i = 0; i < data.Items.length; i++) {
					var existingIndex = StockList.findIndex(item => item.BarcodeNO === data.Items[i].BarcodeNO);

					if (existingIndex === -1) {
						StockList.push({
							TradebarcodeID: data.Items[i].TradebarcodeID,
							BarcodeNO: data.Items[i].BarcodeNO,
							StationNO: data.Items[i].StationNO,
							LampNO: data.Items[i].LampNO,
							ToLampNO: data.Items[i].ToLampNO,
							StorageNO: data.Items[i].StorageNO,
							ToStorageNO: data.Items[i].ToStorageNO,
							Qty: data.Items[i].Qty,
							RState: data.Items[i].RState
						});
					};
				}
				UpdateStockListDisplay();

			} else {
				// console.log("暂无已扫描条码");
			}
			plus.nativeUI.closeWaiting();
		},
		function(error) {

			plus.nativeUI.closeWaiting();
		}
	);
}

/**
 * 绑定输入事件
 * - 当用户在 LampNO 输入框中按下回车键时，将焦点移动到 MaterialCode 输入框
 * - 当用户在 StorageNO 输入框中按下回车键时，将焦点移动到 MaterialCode 输入框
 * - 当用户在 MaterialCode 输入框中按下回车键时，调用 handleMaterialCodeScan 函数处理扫描事件
 */
function bindInputEvents() {
	var isLedMode = document.getElementById('ledModeSwitch').checked;
	// 绑定 LampNO 输入框的 keyup 事件
	$("#LampNO").keyup(function(event) {
		event.preventDefault();
		// 检查是否按下了回车键（keyCode 13）
		if (event.keyCode == 13) {
			// 延迟设置焦点到下一个输入框（可选）
			setTimeout(function() {
				$("#MaterialCode").focus();
			}, 100);
		}
	});

	// 绑定 StorageNO 输入框的 keyup 事件
	$("#StorageNO").keyup(function(event) {
		event.preventDefault();
		// 检查是否按下了回车键（keyCode 13）
		if (event.keyCode == 13) {
			// 延迟设置焦点到下一个输入框（可选）
			var LampNO = $("#LampNO").val();
			setTimeout(function() {
				if (!LampNO) {
					document.getElementById(isLedMode ? 'LampNO' : 'MaterialCode').focus();
				} else {
					$("#MaterialCode").focus();
				}

			}, 100);
		}
	});

	// 绑定 MaterialCode 输入框的 keyup 事件
	$("#MaterialCode").keyup(function(event) {
		event.preventDefault();
		// 检查是否按下了回车键（keyCode 13）
		if (event.keyCode == 13) {
			// 延迟设置焦点到下一个输入框（可选）
			setTimeout(function() {
				// 调用 handleMaterialCodeScan 函数处理扫描事件
				handleMaterialCodeScan();
			}, 100);


		}
	});
	// 设置初始焦点
	//document.getElementById('LampNO').focus();
}

/**
 * 处理 MaterialCode 扫描事件
 * - 获取 LED 模式开关状态
 * - 获取 MaterialCode 输入框的值
 * - 获取货架选项的值
 * - 根据 LED 模式开关状态，获取 ListingNO 的值
 * - 如果 MaterialCode 为空，显示提示信息并重新聚焦到 MaterialCode 输入框
 * - 调用 xccpostAsync 函数发送请求，处理返回的数据
 */
function handleMaterialCodeScan() {
	var IsLed_Mode = document.getElementById('ledModeSwitch').checked;
	var MaterialCode = $("#MaterialCode").val();
	var shelfOption;
	var LampNO = $("#LampNO").val();
	var StorageNO = $("#StorageNO").val();
	var WarehouseID = $("#hToWarehouseID").val();


	if (IsLed_Mode) {
		shelfOption = $("#shelfOption").val();
	} else {
		shelfOption = "-1";

	}

	// 检查 MaterialCode 是否为空
	if (!MaterialCode) {
		mui.toast("Please scan the Material Barcode。", {
			duration: '1000',
			type: 'div'
		});
		$("#MaterialCode").focus();
		return;
	}
	if (MaterialCode.indexOf("||") !== -1) { // 或者用 includes("||")
		MaterialCode = MaterialCode.split("||")[0];
		//console.log("解析到的条码:", firstBarcode); 
	}
	$("#MaterialCode").val(MaterialCode);

	// 检查条码是否在StockList中
	var index = StockList.findIndex(item => item.BarcodeNO === MaterialCode);
	if (index === -1) {
		mui.toast("Barcode not found in current stock list", {
			duration: '1000',
			type: 'div'
		});
		Audios();
		$("#MaterialCode").val('');
		$("#MaterialCode").focus();
		return;
	}
	var isLedMode = document.getElementById('ledModeSwitch').checked;
	// 发送请求
	xccFormPostAsync("api/PDA/TradePutOnBarcode_5", {
		TradeOrderNO: $("#hTradeOrderNO").val(),
		BarcodeNO: MaterialCode,
		UserName: UserName,
		LampNO: LampNO,
		StorageNO: StorageNO,
		WarehouseID: WarehouseID

	}, function(data) {
		document.activeElement.blur();
		if (data.Code === 200) {
			if (isLedMode) {
				$("#LampNO").val(data.Items[0].LampNO);
			}

			StockList[index].ToLampNO = data.Items[0].ToLampNO;
			StockList[index].ToStorageNO = data.Items[0].ToStorageNO;
			StockList[index].RState = "3";
			UpdateStockListDisplay();
			StrCDs();
		} else {
			playSound();
			StrCDs();
		}
		plus.nativeUI.closeWaiting(); // 关闭转圈圈特效
	}, function(error) {
		playSound();
		StrCDs();
		plus.nativeUI.closeWaiting(); // 关闭转圈圈特效
	});

}

function StrCDs() {
	var isLedMode = document.getElementById('ledModeSwitch').checked;
	var isStr = document.getElementById('strCD').checked;
	$("#MaterialCode").val('');
	if (isLedMode) {
		var LampNO = $("#LampNO");

		if (isStr) {
			if (!LampNO)
				$("#LampNO").focus();
			else {
				$("#MaterialCode").focus();
			}
		} else {
			$("#StorageNO").val('');
			$("#StorageNO").focus();
		}
	} else {
		if (isStr) {
			$("#MaterialCode").focus();
		} else {
			$("#StorageNO").val('');
			$("#StorageNO").focus();
		}
	}

}


function toggleLedMode() {
	var isLedMode = document.getElementById('ledModeSwitch').checked;
	const storageGroup = document.getElementById('storageLocationGroup');
	//const ledOptions = document.getElementById('ledModeOptions');

	// 更新开关UI状态
	if (isLedMode) {
		$('.mui-switch').addClass('mui-active');
	} else {
		$('.mui-switch').removeClass('mui-active');
	}
	// 切换显示
	//ledOptions.style.display = isLedMode ? 'block' : 'none';
	storageGroup.style.display = isLedMode ? 'flex' : 'none'; // 关键修改

	// 清空输入并聚焦
	document.getElementById(isLedMode ? 'StorageNO' : 'LampNO').value = '';
	document.getElementById('StorageNO').focus();
}

//删除已扫描条码
function deleteBarcode(BarcodeNO) {
	mui.confirm('Do you want to delete this barcode', 'prompt', function(e) {
		if (e.index == 1) {
			// 检查条码是否在StockList中
			var index = StockList.findIndex(item => item.BarcodeNO === BarcodeNO);
			if (index === -1) {
				mui.toast("Barcode not found in current stock list", {
					duration: '1000',
					type: 'div'
				});
				return;
			}
			xccFormPostAsync("api/PDA/DeleteCode_5", {
				TradeOrderNO: $("#hTradeOrderNO").val(),
				BarcodeNO: BarcodeNO
			}, function(data) {
				if (data.Code == '200') {
					mui.toast("success.", {
						duration: '1000',
						type: 'div'
					});
					StockList[index].RState = "2";
					StockList[index].ToLampNO = '';
					StockList[index].ToStorageNO = '';
					UpdateStockListDisplay();
				} else {
					mui.toast("Delete failed," + data.Message, {
						duration: '1000',
						type: 'div'
					});
				}
				plus.nativeUI.closeWaiting();
			}, function(error) {
				plus.nativeUI.closeWaiting();
			});
		}
	})

}

//失败报警
function Audios() {
	var audio = new Audio('../../../fonts/baojin.mp3');

	audio.play();
}

// 更新交易列表显示
function UpdateStockListDisplay() {
	$("#all").html(""); // 清空显示

	if (StockList.length === 0) {
		$("#all").html(
			'<a style="font-size:100px; color:#F27D48; display:block; text-align:center;" class="mui-icon mui-icon-search"></a><a class="mui-title" style="color:#808080; position: initial; margin: 0 auto; height:' +
			(window.screen.height - 480) + 'px">No data available at the moment</a>');
		return;
	}
	//StockList.sort((a, b) => a.StationNO.localeCompare(b.StationNO));
	StockList.sort((a, b) =>
		a.RState.localeCompare(b.RState, undefined, {
			numeric: true
		}) ||
		a.BarcodeNO.localeCompare(b.BarcodeNO)
	);
	StockList.forEach(item => {
		var itemClass = item.RState == "3" ? 'locked-item' : '';
		var deleteButton = item.RState == "3" ?
			`<button class="soft-delete-btn" onclick="deleteBarcode('${item.BarcodeNO}')">撤销</button>` :
			'';

		$("#all").append(
			`<li class="mui-table-view-cell ${itemClass}">
            <div class="list-container">
                <div class="list-content">
                    <div class="list-title">Code:${item.BarcodeNO}&nbsp;&nbsp;&nbsp;Qty:${item.Qty}</div>
                    <div class="list-detail">ToLampNO:${item.ToLampNO}</div>
                    <div class="list-detail">ToStorageNO:${item.ToStorageNO}</div>
                    ${deleteButton}
                </div>
            </div>
        </li>`
		);
	});
}